package com.xiaodao.springboot.controller;

import com.xiaodao.springboot.entity.User;
import com.xiaodao.springboot.services.ObjectCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/objects")
public class ObjectController {

    @Autowired
    private ObjectCacheService cacheService;

    @GetMapping("/{id}")
    public ResponseEntity<User> getObject(@PathVariable String id) {

        String currentDirectory = System.getProperty("user.dir");
        System.out.println("当前执行目录: " + currentDirectory);
        try {
            User user = cacheService.getObject(id, User.class);
            return ResponseEntity.ok(user);
        } catch (IOException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/{id}")
    public ResponseEntity<String> saveObject(@PathVariable String id, @RequestBody User user) {
        try {
            cacheService.saveObject(id, user);
            return ResponseEntity.ok("Object saved");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Save failed");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteObject(@PathVariable String id) {
        try {
            cacheService.deleteObject(id);
            return ResponseEntity.ok("Object deleted");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Delete failed");
        }
    }
}